package com.example.x6.configurationmaintenance.DataBase.ServiceDaemon;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract;
import java.util.concurrent.atomic.AtomicInteger;

public class ServiceDaemonDatabaseManager {
    private static ServiceDaemonDatabaseManager instance;
    private static SQLiteOpenHelper sqLiteOpenHelper;
    private final String TAG = getClass().getSimpleName();
    private AtomicInteger atomicInteger = new AtomicInteger();
    private SQLiteDatabase sqLiteDatabase;

    public static synchronized void initializeInstance(SQLiteOpenHelper helper) {
        synchronized (ServiceDaemonDatabaseManager.class) {
            if (instance == null) {
                instance = new ServiceDaemonDatabaseManager();
                sqLiteOpenHelper = helper;
            }
        }
    }

    public static synchronized ServiceDaemonDatabaseManager getInstance() {
        ServiceDaemonDatabaseManager serviceDaemonDatabaseManager;
        synchronized (ServiceDaemonDatabaseManager.class) {
            if (instance == null) {
                throw new IllegalStateException(ContactsContract.Data.class.getSimpleName() + " is not initialized, call initializenInstance(...) method first");
            }
            serviceDaemonDatabaseManager = instance;
        }
        return serviceDaemonDatabaseManager;
    }

    public synchronized SQLiteDatabase getWritableDatabase() {
        if (this.atomicInteger.incrementAndGet() == 1) {
            this.sqLiteDatabase = sqLiteOpenHelper.getWritableDatabase();
        }
        return this.sqLiteDatabase;
    }

    public synchronized SQLiteDatabase getReadableDatabase() {
        if (this.atomicInteger.incrementAndGet() == 1) {
            this.sqLiteDatabase = sqLiteOpenHelper.getReadableDatabase();
        }
        return this.sqLiteDatabase;
    }

    public synchronized void closeDatabase() {
        if (this.atomicInteger.decrementAndGet() == 0) {
            this.sqLiteDatabase.close();
        }
    }
}
